package cn.interestingshop.web.manager;

import cn.interestingshop.entity.User;
import cn.interestingshop.service.user.UserService;
import cn.interestingshop.service.user.UserServiceImpl;
import cn.interestingshop.utils.*;
import cn.interestingshop.web.AbstractServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UserServlet",urlPatterns = "/manager/user")
public class UserServlet extends AbstractServlet {

    @Override
    public Class getServletClass() {
        return UserServlet.class;
    }

    private UserService userService = new UserServiceImpl();


    public String index(HttpServletRequest request,HttpServletResponse response){
        /*String id = request.getParameter("")
        userService.getById()*/
        return "/manager/user/userInfo";
    }

    /**
     * 查询用户列表
     * @param request
     * @param response
     * @return
     */
    public String queryUserList(HttpServletRequest request,HttpServletResponse response){
        //调用查询用户列表方法
        //获取当前页
        String currentPage = request.getParameter("currentPage");
        int currentPageNo = EmptyUtils.isEmpty(currentPage)?1:Integer.valueOf(currentPage);
        //获取用户列表
        List<User> allUserList = userService.findAllUserList(currentPageNo, 5);
        //获取总记录条数
        int count = userService.findUserCount();
        Pager pager = new Pager(count,5,currentPageNo);
        pager.setUrl("manager/user?action=queryUserList");
        //将用户列表集合放入request作用域中
        request.setAttribute("userList", allUserList);
        //将pager对象放入request作用域
        request.setAttribute("pager", pager);
        request.setAttribute("menu", 8);    //左侧菜单栏 菜单被选中样式
        return "/manager/user/userList";
    }

    /**
     *  去到新增用户页面
     * @param request
     * @param response
     * @return
     */
    public String toAddUser(HttpServletRequest request,HttpServletResponse response){
        request.setAttribute("user", new User());
        return "/manager/user/toUpdateUser";
    }

    /**
     * 保存用户信息
     * @param request
     * @param response
     * @return
     */
    public ReturnResult updateUser(HttpServletRequest request,HttpServletResponse response){
        ReturnResult returnResult = new ReturnResult();
        //获取页面传递的表单数据
        String id = request.getParameter("id");
        String account = request.getParameter("account");
        String gender = request.getParameter("gender");
        //新增用户时判断用时是否已存在
        User oldUser = userService.getById(null, account);
        boolean flag = EmptyUtils.isNotEmpty(oldUser);
        // id必须为空时，表示现在是新增操作;修改的id与查询到的用户id不一致，表示是新增
        if(EmptyUtils.isNotEmpty(oldUser) && (EmptyUtils.isEmpty(id) || !Integer.valueOf(id).equals(oldUser.getId()))){
            returnResult.returnFail("用户已存在！");
            return returnResult;
        }
        User user = new User();
        user.setAccount(account);
        user.setNickName(request.getParameter("nickName"));
        user.setGender(EmptyUtils.isEmpty(gender) ? 1 : 0);
        if (EmptyUtils.isEmpty(id) || id.equals("0")) {
            //给密码进行MD5加密
            user.setPassword(SecurityUtils.md5Hex(request.getParameter("password")));
        }
        user.setIdCardNo(request.getParameter("idCardNo"));
        user.setEmail(request.getParameter("email"));
        user.setPhone(request.getParameter("phone"));
        user.setType(Integer.parseInt(request.getParameter("type")));
        //新增前调用非空校验方法校验数据的准确性
        returnResult=checkUser(user);
        //是否验证通过
        if(returnResult.getStatus()== Constants.ReturnResult.SUCCESS){
            if (EmptyUtils.isEmpty(id) || id.equals("0")) {
                if(!userService.save(user)){
                    return returnResult.returnFail("增加失败！");
                }
            } else {
                //修改操作
                /*user.setId(Integer.parseInt(id));
                if(!userService.update(user)){
                    return returnResult.returnFail("修改失败！");
                }*/
            }
            returnResult.returnSuccess(); //新增或修改成功
        }
        return returnResult;
    }


    private ReturnResult checkUser(User user){
        ReturnResult result = new ReturnResult();
        if(EmptyUtils.isNotEmpty(user.getPhone())){
            if(!RegUtils.checkphone(user.getPhone())){
                return result.returnFail("手机格式不正确");
            }
        }

        if(EmptyUtils.isNotEmpty(user.getIdCardNo())){
            if(!RegUtils.checkidCardNoReg(user.getIdCardNo())){
                return result.returnFail("身份证号码不正确");
            }
        }

        if(EmptyUtils.isNotEmpty(user.getEmail())){
            if(!RegUtils.checkEmail(user.getEmail())){
                return result.returnFail("邮箱格式不正确");
            }
        }
        return result.returnSuccess();
    }


}
